package walletuserslogic

import (
	"context"
	"github.com/shopspring/decimal"
	"go.uber.org/zap"
	"navi-mumbai/app/rpc/model/pg/wallet"
	"navi-mumbai/common/key/walletkey"
	"navi-mumbai/common/utils"
	"navi-mumbai/common/xerr"

	"navi-mumbai/app/rpc/wallet/internal/svc"
	"navi-mumbai/app/rpc/wallet/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserWalletBalanceLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserWalletBalanceLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserWalletBalanceLogic {
	return &UserWalletBalanceLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 查询用户钱包余额
func (l *UserWalletBalanceLogic) UserWalletBalance(in *pb.UserWalletBalanceReq) (*pb.UserWalletBalanceResp, error) {
	defer utils.RecoverPanic()

	var err error
	var uw *wallet.UserWallet
	uw, err = l.svcCtx.UserWalletModel.FindOneByUidMoneyType(l.ctx, in.Uid, in.MoneyType)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		if err == wallet.ErrNotFound {
			return nil, xerr.NewGrpcErrCodeMsg(xerr.WalletNotFound, "wallet not found")
		}
		return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
	}

	var resp pb.UserWalletBalanceResp
	resp.MoneyType = uw.MoneyType
	resp.Balance = decimal.NewFromInt(uw.Amount).Div(decimal.NewFromInt(walletkey.MoneyScale)).StringFixedBank(2)

	return &resp, nil
}
